package com.example.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.example.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.swing.plaf.PanelUI;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName IndexController
 * @Description TODO
 * @Author: XMK
 * @Date: 2020/4/15 18:58
 * @Version: 1.0
 */
@RestController
@RequestMapping("/")
@Slf4j
public class IndexController {

    @Autowired
    private IndexService service;

    private void initFlowRules() {
        List<FlowRule> list = new ArrayList<>();
        FlowRule rule1 = new FlowRule();
        rule1.setResource("/a/b");
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule1.setCount(2);
        list.add(rule1);

        FlowRule rule2 = new FlowRule();
        rule2.setResource("sentinelV2");
        rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule2.setCount(2);
        list.add(rule2);

        FlowRule rule3 = new FlowRule();
        rule3.setResource("buz");
        rule3.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule3.setCount(1);
        list.add(rule3);

        FlowRuleManager.loadRules(list);
    }

    @PostConstruct
    public void init() {
        initFlowRules();
    }

    @GetMapping("/testsentinelV1")
    public String testsentinelV1() {
        try (Entry entry = SphU.entry("/a/b")) {

            System.out.println("biubiubiubiubiub");

            service.buz();

        } catch (BlockException e) {
            return "sentinel blocked";
        }
        return "ok";
    }

    @GetMapping("/testsentinelV2")
    @SentinelResource(value = "sentinelV2", blockHandler = "testsentinelV2BlockHandler")
    public String testsentinelV2() {
        service.buz();

        return "ok";
    }

    public String testsentinelV2BlockHandler(BlockException e) {
        log.error("V2流量控制：", e);
        return "blocked";
    }
}
